<?php

class User extends CI_Model {

    private $_table = 'users';
    
    public function authenticate($email, $password) {
        $this->load->library('encrypt');
        $key = 'super-secret-key';

        $email = mysql_real_escape_string($email);
        $password = mysql_real_escape_string($password);

        $user = $this->db->select('*')->get_where('users', array(
                    'email' => $email,
                    'password'=>md5($password)
                
                ))->row();
        
        if (count($user) !=0) {
            return $user;
        }
        return false;
    }
        public function login($email, $password) {
        $this->load->library('encrypt');
        $key = 'super-secret-key';

        $email = mysql_real_escape_string($email);
        $password = mysql_real_escape_string($password);

        $user = $this->db->select('*')->get_where('users', array(
                    'email' => $email
                ))->row();
  
        if ($user->password === md5($password)) {
            return true;
        }
        return false;
    }
    
    
    public function guardarUser($arrusuario){
                try {
               $this->db->insert('users', $arrusuario); 
              return $this->db->affected_rows();   
            } catch (Exception $exc) {
                echo $exc->getTraceAsString();
            }
        
    }
    public function changePassword($userData, $userId, $newPassword) {
        $result = false;
        $accessLevel = $userData['userdata']->nivel_acceso;
        $uId = $userData['userdata']->id;
        if ($accessLevel == '1' || $uId == $userId) {
            $user = array(
                'password' => $newPassword
            );
            $this->db->update('users', $user, array('id' => $userId));
            $result = true;
        }
        return $result;
    }

    public function getPasswordByEmail($email) {
        $password = $this->db->select('email, password')->get_where('users', array(
                    'email' => $email
                ))->row();
        return $password;
    }

    public function getProfile($id) {
        $user = $this->db->select('*')->get_where($this->_table, array(
                    'id' => $id
                ))->row();
        return $user;
    }

    function getNumCursosUser($id) {
        return $this->db->query("select * FROM cursos where user_id = '$id'")->num_rows();
    }

    function getTodosCursos($limit, $start) {
        $user_id = $this->session->userdata('user_id');
     
        $return = $this->db->query("select * FROM cursos where user_id = '$user_id' LIMIT $start,$limit")->result();
        return $return;
    }
    function guardarNewsS($arr){
            try {
               $this->db->insert('suscriptors', $arr); 
              return $this->db;   
            } catch (Exception $exc) {
                echo $exc->getTraceAsString();
            }
        
    }
}